package cn.org.rookie.jeesdp.web.handler;

import cn.org.rookie.jeesdp.core.BusinessException;
import cn.org.rookie.jeesdp.web.response.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @author LHT
 * @date 2022-10-12 22:28
 */

@ResponseBody
@ControllerAdvice
public class GlobalExceptionHandler {

    private final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(BusinessException.class)
    public Response handleException(BusinessException e) {
        logger.error(e.getMessage(), e.getException());
        return Response.fail().code(e.getCode()).message(e.getMessage()).data(e.getData());
    }

    @ExceptionHandler(BindException.class)
    public Response handleException(BindException e) {
        logger.error(e.getMessage(), e);
        return buildResponse(e.getBindingResult());
    }

    @ExceptionHandler(Exception.class)
    public Response handleException(Exception e) {
        logger.error(e.getMessage(), e);
        return Response.error().message("服务器异常").data(e.getMessage());
    }


    private Response buildResponse(BindingResult bindingResult) {
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        Response response = Response.fail();
        for (FieldError fieldError : fieldErrors) {
            response.put(fieldError.getField(), fieldError.getDefaultMessage());
        }
        return response;
    }
}
